package com.slipper.common.feign;

import java.nio.charset.StandardCharsets;
import java.util.Map;

import com.slipper.common.exception.CommonException;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.slipper.common.util.GsonUtil;

import feign.Response;
import feign.codec.ErrorDecoder;

public class FeignErrorDecoder implements ErrorDecoder {
    private final Logger logger = LoggerFactory.getLogger(getClass());
    
    @Override
    @SuppressWarnings("rawtypes")
    public Exception decode(String methodKey, Response response) {
        if (response.status() == 401) {
            return new CommonException("服务鉴权失败！");
        }
        Exception exception = null;
        try {
            String json = IOUtils.toString(response.body().asInputStream(), StandardCharsets.UTF_8);
            Map data = GsonUtil.fromJson(json, Map.class);
            this.logger.error("feign调用[{}]出错: {}", methodKey, json);
            String errMsg = (String) data.get("message");
            if (errMsg != null && errMsg.contains("Data truncation")) {
                errMsg = "参数输入过长，请核查！";
            }
            exception = new CommonException(errMsg);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return exception;
    }
}
